/**
 * @ClassName Cal8queens
 * @Description TODO
 * @Author zheng
 * @Date 2021/9/22 11:55
 * @Version 1.0
 **/
public class Cal8queens {
    //结果输入，索引表示行，内容表示放置的列
    int[] result = new int[8];

    public void cal8queens(int row) {
        //第八行放置完毕,结束，打印数据
        if (row == 8) {
            printQueens(result);
            System.out.println("");
            return;
        }
        for (int column = 0; column < 8; column++) {
            if (isOk(row, column)) {
                //row行数据放置的对应列
                result[row] = column;
                //判定下一行是否可行
                cal8queens(row + 1);
            }
        }

    }
    //打印八皇后
    private void printQueens(int[] result) {
        for (int j : result) {
            int k = 0;
            while (k < 8) {
                if (k != j) {
                    System.out.print("* ");
                } else {
                    System.out.print("Q ");
                }
                k++;
            }
            System.out.println("");
        }
    }

    private boolean isOk(int row, int column) {
        //左上角
        int leftUp = column - 1;
        //右上角
        int rightUp = column + 1;
        //遍历之前所有的行
        //前一行的相同列，列-1，列+1是否有值
        //前面第n行的相同列，列-n,列+n 是否有值
        for (int i = row - 1; i >= 0; i--) {
            if (result[i] == column) {
                return false;
            }
            if (leftUp >= 0) {
                if (result[i] == leftUp) {
                    return false;
                }
            }
            if (rightUp < 8) {
                if (result[i] == rightUp) {
                    return false;
                }
            }
            leftUp--;
            rightUp++;
        }
        return true;
    }

    public static void main(String[] args) {
        Cal8queens cal8queens = new Cal8queens();
        cal8queens.cal8queens(0);
    }
}
